package com.ls.fw.data.search.impl.dao.test.data;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.FacetOptions;
import org.springframework.data.solr.core.query.FacetQuery;
import org.springframework.data.solr.core.query.PartialUpdate;
import org.springframework.data.solr.core.query.Query;
import org.springframework.data.solr.core.query.SimpleFacetQuery;
import org.springframework.data.solr.core.query.SimpleField;
import org.springframework.data.solr.core.query.SimpleQuery;
import org.springframework.data.solr.core.query.SimpleStringCriteria;
import org.springframework.data.solr.core.query.result.FacetPage;
import org.springframework.data.solr.example.model.Product;
import org.springframework.data.solr.example.model.SearchableProduct;
import org.springframework.data.solr.example.repository.SolrSearchableFields;
import org.springframework.stereotype.Repository;

import com.ls.fw.data.search.impl.dao.data.SolrDataDaoImpl;

@Repository("productDao")
public class ProductDaoImpl extends SolrDataDaoImpl<Product, String>
		implements ProductDaoCustom {

	@Override
	public Page<Product> findProductsByCustomImplementation(String value,
			Pageable page) {
//		Query query = new SimpleQuery(new SimpleStringCriteria("name:" + value));
//		query.setPageRequest(page);
//		// .ssetPageRequest(page);
//		return this.getSolrOperations().queryForPage(query, Product.class);
		return this.getSolrOperations().queryForPage(new SimpleQuery(new SimpleStringCriteria("name:" + value)).setPageRequest(page),
				Product.class);
	}

	@Override
	public Page<Product> findByPopularity(Integer popularity) {
		Query query = new SimpleQuery(new Criteria(
				SolrSearchableFields.POPULARITY).is(popularity));
		return getSolrOperations().queryForPage(query, Product.class);
	}

	@Override
	public FacetPage<Product> findByNameStartingWithAndFacetOnAvailable(
			String namePrefix) {
		FacetQuery query = new SimpleFacetQuery(new Criteria(
				SolrSearchableFields.NAME).startsWith(namePrefix));
		query.setFacetOptions(new FacetOptions(SolrSearchableFields.AVAILABLE));
		return getSolrOperations().queryForFacetPage(query, Product.class);
	}

	@Override
	public Page<Product> findByAvailableTrue() {
		Query query = new SimpleQuery(new Criteria(new SimpleField(
				Criteria.WILDCARD)).expression(Criteria.WILDCARD));
		query.addFilterQuery(new SimpleQuery(new Criteria(
				SolrSearchableFields.AVAILABLE).is(true)));
		return getSolrOperations().queryForPage(query, Product.class);
	}
	
	@Override
	public void updateProductCategory(String productId, List<String> categories) {
		PartialUpdate update = new PartialUpdate(SearchableProduct.ID_FIELD, productId);
		update.setValueOfField(SearchableProduct.CATEGORY_FIELD, categories);

		getSolrOperations().saveBean(update);
		getSolrOperations().commit();
	}
}
